package m.jclecai.com.fragment;

import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseFragment;
import m.jclecai.com.bean.TrendButtonBean;
import m.jclecai.com.bean.TrendDataBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.contents.LotteryType;
import m.jclecai.com.utils.LotteryTrendUtils;
import m.jclecai.com.utils.MyToast;
import m.jclecai.com.utils.ScreenUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.utils.http.SystemUtils;
import m.jclecai.com.utils.http.responseBody.BaseBody;
import m.jclecai.com.view.DDTrendChart;
import m.jclecai.com.view.LottoTrendView;

/**
 * Created by ZD on 2017/4/26.
 */

public class LottoTrendFragment extends BaseFragment {

    @BindView(R.id.ltv_trendView)
    LottoTrendView ltvTrendView;
    @BindView(R.id.rg_num)
    RadioGroup rgNum;

    @BindView(R.id.lotteryBody)
    View lotteryBody;
    private DDTrendChart mTrendChart;

    //彩票种类id
    String lotteryid = "3";
    //期数
    String issuecount = "30";
    //所选按钮参数
    String idx = "num_info1";
    int numCount = 0;
    int startIndex = 0;
    TrendButtonBean bean;
    boolean isUniform = true;
    int numBg = -1;
    boolean addZero = false;
    boolean canZero = true;
    boolean numAddZero = false;
    private String mHidX;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_lotto_trend;
    }

    @Override
    public void initView() {
        this.mTrendChart = new DDTrendChart(getActivity(), this.ltvTrendView);
        this.ltvTrendView.setChart(this.mTrendChart);
        this.mTrendChart.setShowYilou(true);
        this.mTrendChart.setDrawLine(true);

        if (bean != null) {
            addRadioButton(bean);
        }
    }

    public void setTrendData(TrendButtonBean data) {
        bean = data;
    }

    /**
     * 动态为顶部的ViewGroup添加按钮
     *
     * @param bean
     */
    void addRadioButton(TrendButtonBean bean) {
        int width = ScreenUtil.getScreenWidth(getActivity());
        for (int i = 0; i < bean.getNames().length; i++) {
            lotteryid = String.valueOf(bean.getLotteryid());
            RadioButton rb = new RadioButton(getActivity());
            rgNum.addView(rb, new LinearLayout.LayoutParams(width / bean.getNames().length, LinearLayout.LayoutParams.MATCH_PARENT, 1.0f));
            rb.setCompoundDrawablesWithIntrinsicBounds(null, null, null, ContextCompat.getDrawable(getActivity(), R.drawable.tab_radio_driver));
            rb.setButtonDrawable(R.color.transparent);
            rb.setTextColor(ContextCompat.getColor(getActivity(), R.color.color_333));
            rb.setGravity(Gravity.CENTER);
            rb.setText(bean.getNames()[i]);
            String param = new Gson().toJson(bean) + "_" + i;
            rb.setTag(param);
            rb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String s = v.getTag().toString();
                    String json = s.substring(0, s.lastIndexOf("_"));
                    String id = s.substring(s.lastIndexOf("_") + 1);
                    int index = Integer.parseInt(id);
                    TrendButtonBean b = new Gson().fromJson(json, TrendButtonBean.class);
                    idx = b.getIdxs()[index];
                    isUniform = b.getIsUniform()[index];
                    numBg = ContextCompat.getColor(getActivity(), b.getNumBg()[index]);
                    addZero = b.isAddZero();
                    canZero = b.isCanZero();
                    numAddZero = b.isNumAddZero();
                    mHidX = b.getHidxs()[index];
                    loadData();
                }
            });
            if (i == bean.getCheckIndex()) {
                rgNum.check(rb.getId());
                idx = bean.getIdxs()[i];
                mHidX = bean.getHidxs()[i];
                isUniform = bean.getIsUniform()[i];
                numBg = ContextCompat.getColor(getActivity(), bean.getNumBg()[i]);
                addZero = bean.isAddZero();
                canZero = bean.isCanZero();
                numAddZero = bean.isNumAddZero();
                loadData();
            }
        }
    }

    @Override
    public void loadData(String issuecount) {
        super.loadData(issuecount);
        this.issuecount = issuecount;
        loadData();
    }

    //加载数据
    private void loadData() {
        showDialog();
        Map<String, String> map = new HashMap<>();
        map.put("lotteryid", lotteryid);
        map.put("issuecount", issuecount);
        map.put("idx", idx);
        HttpManager.postAsyn(Constant_Url.BOUNS_CODE, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                MyToast.showToast(getActivity(), getString(R.string.error_network));
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                BaseBody baseBody = FastOk.get(response, BaseBody.class);
                if (baseBody != null && baseBody.getStatus() == 0) {

                    ArrayList<TrendDataBean> trendDataBeen = string2JsonArray(response);

                    if(bean.getLotteryid() == LotteryType.AHKS ||
                            bean.getLotteryid() == LotteryType.HBKS ||
                            bean.getLotteryid() == LotteryType.JLKS ||
                            bean.getLotteryid() == LotteryType.JSKS
                            ){

                        //这里是江苏快三，是需要全屏显示的；
                        mTrendChart.updateData(trendDataBeen, isUniform, numCount, addZero,
                                canZero, startIndex, numBg, numAddZero, lotteryid.equals("71"), idx);
                        //设置默认最大的缩小；

                    }else{

                        //这里是江苏快三，是需要全屏显示的；
                        mTrendChart.updateData(trendDataBeen, isUniform, numCount, addZero,
                                canZero, startIndex, numBg, numAddZero, lotteryid.equals("71"), idx);
                    }
                    if(trendDataBeen.size()>20){
                        //缩小操作；
                        ltvTrendView.cal(20,100);
                    }
                } else {
                    MyToast.showToast(getActivity(), getString(R.string.error_network));
                }

            }
        }, map);
    }

    /**
     * 字符串序列化成jsonArray
     *
     * @param content
     * @return
     */
    ArrayList<TrendDataBean> string2JsonArray(String content) {
        ArrayList<TrendDataBean> list = new ArrayList<>();
        try {
            content = SystemUtils.jsonp2JsonString(content);
            numCount = 0;
            startIndex = 0;
            JsonObject jsonObject = new Gson().fromJson(content, JsonObject.class);
            //号码球
            JsonArray alldiffs = jsonObject.getAsJsonArray("alldiffs");
            //期号
            JsonArray infolist = jsonObject.getAsJsonArray("infolist");

            //大乐透是12
            //双色球是11
            //七乐彩是10
            if (idx.contains("area1")) {
                if (lotteryid.equals("19"))//大乐透
                    startIndex = 0;
                if (lotteryid.equals("16"))//双色球
                    startIndex = 0;
                if (lotteryid.equals("17"))//七乐彩
                    startIndex = 0;
            } else if (idx.contains("area2")) {
                if (lotteryid.equals("19"))//大乐透
                    startIndex = 12;
                if (lotteryid.equals("16"))//双色球
                    startIndex = 11;
                if (lotteryid.equals("17"))//七乐彩
                    startIndex = 10;
            } else if (idx.contains("area3")) {
                if (lotteryid.equals("19"))//大乐透
                    startIndex = 24;
                if (lotteryid.equals("16"))//双色球
                    startIndex = 22;
                if (lotteryid.equals("17"))//七乐彩
                    startIndex = 20;
            }

            //这里是对应的一期的期号

            for (int i = 0; i < alldiffs.size(); i++) {

                //JsonElement jsonElement = infolist.getString(idx);

                TrendDataBean trendDataBean = new TrendDataBean();
                JsonArray ads = alldiffs.get(i).getAsJsonArray();
                JsonObject ifl = infolist.get(i).getAsJsonObject();

                //在这里我们要做的一个事情就是，我们要判断一下这个页面的一行需要显示多少个小球，注意这波操作；
                List<Integer> positionList = getAwardBallList(ifl);

                //这个是具体的中奖的位置；
                String lottery_num = ifl.get(mHidX).getAsString();

                int position = Integer.parseInt(lottery_num) - 1;

                String blue = "";
                numCount = ads.size();
                for (int j = 0; j < ads.size(); j++) {
                    //胜负彩规则不同
                    if (lotteryid.equals("71")) {
                        if (ifl.get("num_info" + (j + 1)).getAsString().equals(idx)) {
                            blue += "0";
                        } else {
                            blue += "";
                        }
                    } else {
                        //将中奖号码设置未-1
                      /*  if (j == position) {
                            blue += "-1";
                        } else {
                            blue += ads.get(j).getAsString();
                        }*/

                        if (positionList.contains(j + startIndex)) {
                            blue += "-1";
                        } else {
                            blue += ads.get(j).getAsString();
                        }
                    }
                    if (j < ads.size() - 1)
                        blue += ",";
                }
                trendDataBean.setBlue(blue);
                trendDataBean.setPid(ifl.get("lottery_num").getAsString());
                trendDataBean.setType("row");
                list.add(trendDataBean);
            }
            //出现总次数
            JsonArray placenum = jsonObject.getAsJsonArray("placenum");
            TrendDataBean trendDataBean = new TrendDataBean();
            trendDataBean.setBlue(jsonArray2String(placenum));
            trendDataBean.setType("dis");
            list.add(trendDataBean);

            //平均遗漏值
            JsonArray average_omission = jsonObject.getAsJsonArray("average_omission");
            trendDataBean = new TrendDataBean();
            trendDataBean.setBlue(jsonArray2String(average_omission));
            trendDataBean.setType("avg");
            list.add(trendDataBean);

            //最大遗漏值
            JsonArray max_omission = jsonObject.getAsJsonArray("max_omission");
            trendDataBean = new TrendDataBean();
            trendDataBean.setBlue(jsonArray2String(max_omission));
            trendDataBean.setType("mmv");
            list.add(trendDataBean);

            //最大连出值
            JsonArray max_output = jsonObject.getAsJsonArray("max_output");
            trendDataBean = new TrendDataBean();
            trendDataBean.setBlue(jsonArray2String(max_output));
            trendDataBean.setType("mlv");
            list.add(trendDataBean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 这里我们要做一个操作就是返回当前区域中奖的号码的位置的集合
     *
     * @param ifl
     * @return
     */
    private List<Integer> getAwardBallList(JsonObject ifl) {

        LotteryTrendUtils lotteryTrendUtils = new LotteryTrendUtils(lotteryid, ifl, mHidX, idx);
        return lotteryTrendUtils.getAwardBallList();

     /*   ArrayList<Integer> integers = new ArrayList<>();*/
        //这里先将所有的可能性取出来；
/*       if("19".equals(lotteryid)){
            //这里表示的大乐透
        }else if("16".equals(lotteryid)){
            //双色球
        }else if("17".equals(lotteryid)){
            //七乐彩；
        }
        不管是双色球，还是大乐透，还是七乐彩，都是有七个小球，
        其中大乐透最后两个小球是蓝色的，
        双色球最后一个小球是蓝色的；
        七乐彩是没有篮球的；*/
/*
        if ("19".equals(lotteryid)) {
            //这里表示大乐透
            return createDLTAwardBallList(ifl);
        } else if ("16".equals(lotteryid)) {
            //双色球
            return createSSQAwardBallList(ifl);
        } else if ("17".equals(lotteryid)) {
            //七乐彩；
            return createQLCAwardBallList(ifl);
        } else if("18".equals(lotteryid)){
            //七星彩
            return createQXCAwardBallList(ifl);
        }else if("2".equals(ifl)){
            //排列三；
            return ceratePlsAwardBallList(ifl);
        }else {
            //默认的处理方式；
            return createAwardBallList(ifl);
        }*/
    }

    private List<Integer> ceratePlsAwardBallList(JsonObject ifl) {
        ArrayList<Integer> ballList = new ArrayList<>();
        String lottery_num = ifl.get(mHidX).getAsString();
        int position = Integer.parseInt(lottery_num);
        ballList.add(position);
        return ballList;
    }

    //七星彩；
    private List<Integer> createQXCAwardBallList(JsonObject ifl) {
        ArrayList<Integer> ballList = new ArrayList<>();
        String lottery_num = ifl.get(idx).getAsString();
        int position = Integer.parseInt(lottery_num);
        ballList.add(position);
        return ballList;
    }

    /**
     * 这里我们是做默认的处理方法方式
     *
     * @param ifl
     * @return
     */
    private List<Integer> createAwardBallList(JsonObject ifl) {
        ArrayList<Integer> ballList = new ArrayList<>();
        String lottery_num = ifl.get(mHidX).getAsString();
        int position = Integer.parseInt(lottery_num);
        ballList.add(position);
        return ballList;
    }

    /**
     * 七乐彩的操作；
     *
     * @return
     */
    private List<Integer> createQLCAwardBallList(JsonObject ifl) {

        ArrayList<Integer> redBallList = new ArrayList<>();
        ArrayList<Integer> ballList = new ArrayList<>();

        String num_info1 = ifl.get("num_info1").getAsString();
        String num_info2 = ifl.get("num_info2").getAsString();
        String num_info3 = ifl.get("num_info3").getAsString();
        String num_info4 = ifl.get("num_info4").getAsString();
        String num_info5 = ifl.get("num_info5").getAsString();
        String num_info6 = ifl.get("num_info6").getAsString();
        String num_info7 = ifl.get("num_info7").getAsString();

        redBallList.add(Integer.parseInt(num_info1) - 1);
        redBallList.add(Integer.parseInt(num_info2) - 1);
        redBallList.add(Integer.parseInt(num_info3) - 1);
        redBallList.add(Integer.parseInt(num_info4) - 1);
        redBallList.add(Integer.parseInt(num_info5) - 1);

        redBallList.add(Integer.parseInt(num_info6) - 1);
        redBallList.add(Integer.parseInt(num_info7) - 1);

        if (idx.equals("area1")) {
            //红一
            return getAreaPositionList(0, 9, redBallList);
        } else if (idx.equals("area2")) {
            //红二
            return getAreaPositionList(10, 19, redBallList);
        } else if (idx.equals("area3")) {
            //红三
            return getAreaPositionList(20, 29, redBallList);
        }
        return ballList;
    }

    /**
     * 七乐彩的选中小球的数量；
     *
     * @param ifl
     * @return
     */
    private List<Integer> createDLTAwardBallList(JsonObject ifl) {

        //这里我们要做的就是双色球的返回值的第一个操作；
        ArrayList<Integer> ballList = new ArrayList<>();

        ArrayList<Integer> redBallList = new ArrayList<>();
        ArrayList<Integer> blueBallList = new ArrayList<>();

        String num_info1 = ifl.get("num_info1").getAsString();
        String num_info2 = ifl.get("num_info2").getAsString();
        String num_info3 = ifl.get("num_info3").getAsString();
        String num_info4 = ifl.get("num_info4").getAsString();
        String num_info5 = ifl.get("num_info5").getAsString();
        String num_info6 = ifl.get("num_info6").getAsString();
        String num_info7 = ifl.get("num_info7").getAsString();

        redBallList.add(Integer.parseInt(num_info1) - 1);
        redBallList.add(Integer.parseInt(num_info2) - 1);
        redBallList.add(Integer.parseInt(num_info3) - 1);
        redBallList.add(Integer.parseInt(num_info4) - 1);
        redBallList.add(Integer.parseInt(num_info5) - 1);

        blueBallList.add(Integer.parseInt(num_info6) - 1);
        blueBallList.add(Integer.parseInt(num_info7) - 1);

        //判断是红球还是篮球；
        if (idx.equals("area1")) {
            //红一
            return getAreaPositionList(0, 11, redBallList);
        } else if (idx.equals("area2")) {
            //红二
            return getAreaPositionList(12, 23, redBallList);
        } else if (idx.equals("area3")) {
            //红三
            return getAreaPositionList(24, 34, redBallList);
        } else if (idx.equals("back")) {
            //篮区
            return blueBallList;
        }
        return ballList;
    }


    private List<Integer> createSSQAwardBallList(JsonObject ifl) {
        //这里我们要做的就是双色球的返回值的第一个操作；
        ArrayList<Integer> ballList = new ArrayList<>();

        ArrayList<Integer> redBallList = new ArrayList<>();
        ArrayList<Integer> blueBallList = new ArrayList<>();

        String num_info1 = ifl.get("num_info1").getAsString();
        String num_info2 = ifl.get("num_info2").getAsString();
        String num_info3 = ifl.get("num_info3").getAsString();
        String num_info4 = ifl.get("num_info4").getAsString();
        String num_info5 = ifl.get("num_info5").getAsString();
        String num_info6 = ifl.get("num_info6").getAsString();
        String num_info7 = ifl.get("num_info7").getAsString();

        redBallList.add(Integer.parseInt(num_info1) - 1);
        redBallList.add(Integer.parseInt(num_info2) - 1);
        redBallList.add(Integer.parseInt(num_info3) - 1);
        redBallList.add(Integer.parseInt(num_info4) - 1);
        redBallList.add(Integer.parseInt(num_info5) - 1);
        redBallList.add(Integer.parseInt(num_info6) - 1);

        blueBallList.add(Integer.parseInt(num_info7) - 1);


        //判断是红球还是篮球；
        if (idx.equals("area1")) {
            //红一
            return getAreaPositionList(0, 10, redBallList);
        } else if (idx.equals("area2")) {
            //红二
            return getAreaPositionList(11, 21, redBallList);
        } else if (idx.equals("area3")) {
            //红三
            return getAreaPositionList(22, 32, redBallList);
        } else if (idx.equals("num_info7")) {
            //篮区
            return blueBallList;
        }
        return ballList;
    }

    public List<Integer> getAreaPositionList(int start, int end, List<Integer> awardList) {
        //这里我们是将符合要求的中奖号码的位置返回
        ArrayList<Integer> integers = new ArrayList<>();

        for (Integer integer : awardList) {
            //将符合要求的位置添加到一个集合中；
            if (integer >= start && integer <= end) {
                integers.add(integer);
            }
        }
        return integers;
    }

    /**
     * 将数组转成字符串
     *
     * @param jsonArray
     * @return
     */
    String jsonArray2String(JsonArray jsonArray) {
        String blue = "";
        for (int i = 0; i < jsonArray.size(); i++) {
            blue += jsonArray.get(i).getAsString();
            if (i < jsonArray.size() - 1)
                blue += ",";
        }
        return blue;
    }
}
